package com.lei.leetcode;

import java.util.TreeMap;

/**
 * @Author LeiXiaoLei
 * @Date 2022/8/30 10:12
 * @Version 1.0
 */
public class S_211 {
    private class Node {
        public boolean isWord;
        public TreeMap<Character, Node> next;

        public Node(boolean isWord) {
            this.isWord = isWord;
            next = new TreeMap<>();
        }

        public Node() {
            this(false);
        }
    }

    private Node root;

    public S_211() {
        root = new Node();
    }

    public void addWord(String word) {
        Node current = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (current.next.get(c) == null) current.next.put(c, new Node());
            current = current.next.get(c);
        }
        current.isWord = true;
    }

    public boolean search(String word) {
        return match(root, word, 0);
    }

    private boolean match(Node node, String word, int index) {
        if (index == word.length()) return node.isWord;
        char c = word.charAt(index);
        if (c != '.') {
            if (node.next.get(c) == null) return false;
            return match(node.next.get(c), word, index + 1);
        } else {
            for (char nextChar : node.next.keySet()) {
                if (match(node.next.get(nextChar), word, index + 1)) return true;
            }
        }
        return false;
    }
}
